package com.zf.shuashua.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.lxj.xpopup.util.KeyboardUtils;
import com.meis.base.mei.adapter.BaseMultiAdapter;
import com.meis.base.mei.base.BaseMultiListFragment;
import com.meis.base.mei.constant.DataConstants;
import com.meis.base.mei.entity.Result;
import com.meis.base.mei.status.ViewState;
import com.meis.base.mei.utils.ParseJsonUtils;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.R;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.advert.AdvertConstants;
import com.zf.shuashua.advert.CommitUtils;
import com.zf.shuashua.advert.InteractionAdListener;
import com.zf.shuashua.advert.NativeAdvertByteManager;
import com.zf.shuashua.advert.NativeAdvertTencentManager;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.bean.advert.AdvertConfigBean;
import com.zf.shuashua.bean.comment.CommentEntity;
import com.zf.shuashua.bean.comment.CommentListEntity;
import com.zf.shuashua.ui.adapter.CommentAdapter;
import com.zf.shuashua.ui.dialog.BottomCommentDialog;
import com.zf.shuashua.ui.dialog.BottomOperateDialog;
import com.zf.shuashua.ui.mine.LoginActivity;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;

public class CommentListFragment extends BaseMultiListFragment<CommentEntity> {

    public static final String VIDEO_ID = "video_id";
    private RecyclerView mRecyclerView;
    private CommentAdapter mAdapter;
    private String videoId = "";
    private boolean isItemEmptyPage = false;
    private BottomCommentDialog mBottomCommentDialog;

    public static CommentListFragment newInstance(String articleId) {
        Bundle args = new Bundle();
        args.putString(VIDEO_ID, articleId);
        CommentListFragment fragment = new CommentListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public boolean isItemEmptyPage() {
        return isItemEmptyPage;
    }

    public void setItemEmptyPage(boolean itemEmptyPage) {
        isItemEmptyPage = itemEmptyPage;
    }

    @Override
    protected void initView() {
        setState(ViewState.EMPTY);
        if (getArguments() != null) {
            videoId = getArguments().getString(VIDEO_ID, "");
        }
        super.initView();
    }

    @Override
    protected void initData() {
        requestAdData();
    }

    @Override
    protected void onDataLoaded(int pageNo, Result<List<CommentEntity>> result) {
        super.onDataLoaded(pageNo, result);
        setState(ViewState.COMPLETED);
    }

    // 请求广告数据
    private void requestAdData() {
        if (ShuaApplication.horizontalConfig == null) {
            requestDefaultAdData();
            return;
        }
        //轮询依次获取横屏信息流的广告配置
        AdvertConfigBean advertConfig = ShuaApplication.horizontalConfig.getCommonHorizontalConfig();
        if (advertConfig == null) {
            requestDefaultAdData();
            return;
        }
        String advertId = advertConfig.getOrigin_id();
        if (advertConfig.isTencent()) {
            loadTencentNativeAd(advertId);
        } else {
            loadByteNativeAd(advertId);
        }
    }

    private void requestDefaultAdData() {
        loadByteNativeAd("");
    }

    private void loadByteNativeAd(String advertId) {
        if(CommitUtils.isVivoClose() || CommitUtils.isHuaweiClose() || CommitUtils.isOppoClose()){
            return;
        }
        if (TextUtils.isEmpty(advertId)) {
            advertId = "945420044";
        }
        NativeAdvertByteManager.getInstance().loadFullExpressAd(mActivity, AdvertConstants.NATIVE_TYPE_HOT, advertId, new InteractionAdListener() {
            @Override
            public void onRenderSuccess(View view) {
                mAdapter.removeAllHeaderView();
                mAdapter.addHeaderView(view, 0);
                mRecyclerView.scrollToPosition(0);
            }

            @Override
            public void onError() {

            }
        });
    }

    private void loadTencentNativeAd(String advertId) {
        if(CommitUtils.isVivoClose() || CommitUtils.isHuaweiClose() || CommitUtils.isOppoClose()){
            return;
        }
        if (TextUtils.isEmpty(advertId)) {
            advertId = "7071747407734394";
        }
        NativeAdvertTencentManager.getInstance().loadFullExpressAd(mActivity, AdvertConstants.NATIVE_TYPE_HOT, advertId, new InteractionAdListener() {
            @Override
            public void onRenderSuccess(View view) {
                mRecyclerView.postDelayed(() -> {
                    mAdapter.removeAllHeaderView();
                    mAdapter.addHeaderView(view, 0);
                    mRecyclerView.scrollToPosition(0);
                }, 400);
            }

            @Override
            public void onError() {

            }
        });
    }


    @Override
    protected RecyclerView getRecyclerView() {
        mRecyclerView = getView().findViewById(R.id.recycler);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        return mRecyclerView;
    }

    @Override
    protected BaseMultiAdapter<CommentEntity> getAdapter() {
        return mAdapter = new CommentAdapter(new CommentAdapter.OnViewClickListener() {
            @Override
            public void onPraise(View view, boolean isLevel2Reply, String id, int position) {
                if (!Store.getInstance().isLogin()) {
                    jumpLogin();
                    return;
                }
                HttpData.getInstance().commentPraise(isLevel2Reply, id, new ACallback<BaseData<CommentEntity>>() {

                    @Override
                    public void onSuccess(BaseData<CommentEntity> data) {
                        if (data.getCode() == 200) {
                            if (data.getData() != null) {
                                int headerCount = mAdapter.getHeaderLayoutCount();
                                int updatePosition = position - headerCount;
                                if (updatePosition <= 0) updatePosition = 0;
                                mAdapter.getData().get(updatePosition).is_praise_user = data.getData().is_praise_user;
                                mAdapter.getData().get(updatePosition).praise_count = data.getData().praise_count;
                                mAdapter.notifyItemChanged(position);
                            }
                        } else if (data.getCode() == 401) {
                            if (!Store.getInstance().isLogin()) {
                                jumpLogin();
                            }
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                    }
                });
            }

            @Override
            public void onLong(View view, boolean isLevel2Reply, String userId, String id, int position, String content) {
                boolean isOwn = Store.getInstance().getuserId().equals(userId);
                showDialog(new BottomOperateDialog(isOwn, isLevel2Reply, id, position, content, (v, position1) -> {
                    position1 = position1 - mAdapter.getHeaderLayoutCount();
                    if (position1 <= 0) position1 = 0;
                    int deleteNum = 1;
                    if (!isLevel2Reply) {
                        // 删除所有二级评论
                        List<CommentEntity> deleteList = new ArrayList<>();
                        for (int i = position1; i < mAdapter.getData().size(); i++) {
                            CommentEntity bean = mAdapter.getData().get(i);
                            if (bean.id.equals(id) || bean.parentIdHelper.equals(id)) {
                                deleteList.add(bean);
                            } else {
                                break;
                            }
                        }
                        deleteNum += mAdapter.getData().get(position1).reply_count;
                        mAdapter.getData().removeAll(deleteList);
                        mAdapter.notifyItemRangeRemoved(position1 + mAdapter.getHeaderLayoutCount(), deleteList.size());
                    } else {
                        // 自动更新回复数量 -1
                        for (int i = position1; i >= 0; i--) {
                            CommentEntity bean = mAdapter.getData().get(i);
                            if (bean.itemType == CommentAdapter.TYPE_LEVEL_1) {
                                bean.reply_count -= 1;
                                bean.reply_count = bean.reply_count <= 0 ? 0 : bean.reply_count;
                                break;
                            }
                        }
                        if (mAdapter.getData().size() > position1) {
                            mAdapter.remove(position1);
                        }
                    }

                    if (mOperateListener != null) {
                        mOperateListener.onDeleteComment(deleteNum);
                    }

                    if (mAdapter.getData().isEmpty()) {
                        setState(ViewState.EMPTY);
                    }
                }));
            }

            @Override
            public void onReply(View view, String userId, String id, String userName, boolean isLevel2Reply, int position) {
                if (!Store.getInstance().isLogin()) {
                    jumpLogin();
                    return;
                }

                showDialog(mBottomCommentDialog = new BottomCommentDialog(id, userId, position, userName, true, isLevel2Reply, new BottomCommentDialog.OnPublishListener() {
                    @Override
                    public void onPublish(int pos, boolean isAt, boolean isLevel2Reply, CommentEntity entity) {
                        int headerCount = mAdapter.getHeaderLayoutCount();
                        pos = pos - headerCount;
                        if (isAt && entity != null && (pos + 1) <= mAdapter.getData().size()) {
                            // 自动更新回复数量 +1
                            for (int i = pos; i >= 0; i--) {
                                CommentEntity bean = mAdapter.getData().get(i);
                                if (bean.itemType == CommentAdapter.TYPE_LEVEL_1) {
                                    bean.reply_count += 1;
                                    break;
                                }
                            }

                            entity.itemType = CommentAdapter.TYPE_LEVEL_2;
                            entity.isLevel2ReplyHelper = isLevel2Reply;

                            mAdapter.addData(pos + 1, entity);
                            mRecyclerView.smoothScrollToPosition(pos + 1 + headerCount);

                            // 更新评论数量
                            if (mOperateListener != null) mOperateListener.onAddReply();
                        }
                    }

                    @Override
                    public void onCloseKeyboard() {
                        mRecyclerView.postDelayed(() -> KeyboardUtils.hideSoftInput(getActivity()), 100);
                    }
                }));

            }

            @Override
            public void onLoadMore(View view, String id, int page, int limit, String filterId, int position) {
                if (TextUtils.isEmpty(id)) return;
                HttpData.getInstance().getReplyListData(id, page, limit, new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        int headerCount = mAdapter.getHeaderLayoutCount();
                        int pos = position - headerCount;
                        if (pos <= 0) pos = 0;
                        if (!TextUtils.isEmpty(data)) {
                            List<CommentEntity> replyList = ParseJsonUtils.parseListData(data, "data", CommentEntity.class);
                            if (replyList.isEmpty()) {
                                mAdapter.remove(pos);
                                return;
                            }
                            mAdapter.getData().get(pos).currentPageHelper += 1;

                            // 添加二级回复列表
                            if (page == 1) {
                                // 移除第一条数据
                                // replyList.remove(0);
                                for (CommentEntity entity : replyList) {
                                    if (entity.id.equals(filterId)) {
                                        replyList.remove(entity);
                                        break;
                                    }
                                }
                            }

                            if (replyList.isEmpty()) return;
                            for (CommentEntity entity : replyList) {
                                entity.itemType = CommentAdapter.TYPE_LEVEL_2;
                                entity.parentIdHelper = id;
                            }
                            mAdapter.addData(pos, replyList);

                            // 无更多数据
                            if (replyList.size() < (page == 1 ? (limit - 1) : limit)) {
                                mAdapter.remove(pos + replyList.size());
                            }
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                    }
                });
            }
        });
    }

    private void jumpLogin() {
        getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
    }

    public void removeItemEmpty() {
        int index = 0;
        for (int i = 0; i < mAdapter.getData().size(); i++) {
            if (mAdapter.getData().get(i).itemType == CommentAdapter.TYPE_EMPTY) {
                index = i;
                break;
            }
        }
        mAdapter.remove(index);
    }

    @Override
    protected boolean isFirstShowMoreEnd() {
        return true;
    }

    public void insertData(int pos, CommentEntity entity) {
        if (mAdapter != null) {
            setState(ViewState.COMPLETED);
            mAdapter.addData(pos, entity);
            mRecyclerView.smoothScrollToPosition(pos);
        }
    }

    @Override
    protected Observable<Result<List<CommentEntity>>> getListObservable(int pageNo) {
        Observable<String> observable = HttpData.getInstance().getCommentList(pageNo, videoId);
        return getListData(observable, pageNo);
    }


    private Observable<Result<List<CommentEntity>>> getListData(Observable<String> observable, int pageNo) {
        final Result<List<CommentEntity>> result = new Result<>();
        return observable.map(s -> {
            if (!TextUtils.isEmpty(s)) {
                try {
                    List<CommentEntity> resultList = new ArrayList<>();
                    CommentListEntity entity = ParseJsonUtils.parseData(s, CommentListEntity.class);
                    if (entity.meta != null && entity.meta.meta != null) {
                        CommentListEntity.Meta2 meta2 = entity.meta.meta;
                        if (meta2.top_comment != null) {
                            resultList.add(meta2.top_comment);
                            if (meta2.top_comment.reply_first != null) {
                                meta2.top_comment.reply_first.itemType = CommentAdapter.TYPE_LEVEL_2;
                                meta2.top_comment.reply_first.parentIdHelper = meta2.top_comment.id;
                                resultList.add(meta2.top_comment.reply_first);

                                if (meta2.top_comment.reply_count > 1) {
                                    CommentEntity expandEntity = new CommentEntity();
                                    expandEntity.itemType = CommentAdapter.TYPE_EXPAND_MORE;
                                    expandEntity.currentPageHelper = 1;
                                    expandEntity.id = meta2.top_comment.id;
                                    resultList.add(expandEntity);
                                }
                            }
                        }

                        if (meta2.hots_comment != null && !meta2.hots_comment.isEmpty()) {
                            for (CommentEntity bean : meta2.hots_comment) {
                                resultList.add(bean);
                                if (bean.reply_first != null) {
                                    bean.reply_first.itemType = CommentAdapter.TYPE_LEVEL_2;
                                    bean.reply_first.parentIdHelper = bean.id;
                                    resultList.add(bean.reply_first);
                                    if (bean.reply_count > 1) {
                                        CommentEntity expandEntity = new CommentEntity();
                                        expandEntity.itemType = CommentAdapter.TYPE_EXPAND_MORE;
                                        expandEntity.currentPageHelper = 1;
                                        expandEntity.id = bean.id;
                                        resultList.add(expandEntity);
                                    }
                                }
                            }
                            //resultList.addAll(meta2.hots_comment);
                        }
                    }
                    if (entity.data != null) {
                        for (CommentEntity bean : entity.data) {
                            resultList.add(bean);
                            if (bean.reply_first != null) {
                                bean.reply_first.itemType = CommentAdapter.TYPE_LEVEL_2;
                                bean.reply_first.parentIdHelper = bean.id;
                                resultList.add(bean.reply_first);
                                if (bean.reply_count > 1) {
                                    CommentEntity expandEntity = new CommentEntity();
                                    expandEntity.itemType = CommentAdapter.TYPE_EXPAND_MORE;
                                    expandEntity.currentPageHelper = 1;
                                    expandEntity.id = bean.id;
                                    resultList.add(expandEntity);
                                }
                            }
                        }
                        //resultList.addAll(entity.data);
                    }

                    if (pageNo == DataConstants.FIRST_PAGE && resultList.isEmpty()) {
                        isItemEmptyPage = true;
                        CommentEntity empty = new CommentEntity();
                        empty.itemType = CommentAdapter.TYPE_EMPTY;
                        resultList.add(empty);
                    }

                    result.data = resultList;
                } catch (Exception e) {
                }
            }
            return result;
        });
    }

    @Override
    protected boolean loadOnShow() {
        return false;
    }

    @Override
    public boolean canLoadMore() {
        return true;
    }

    @Override
    public boolean canPullToRefresh() {
        return false;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_list_comm_recycler;
    }

    private OnOperateListener mOperateListener;

    public void setOnOperateListener(OnOperateListener listener) {
        mOperateListener = listener;
    }

    public interface OnOperateListener {
        void onDeleteComment(int deleteNum);

        void onAddReply();
    }
}
